package crypto

import (
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha256"
	"encoding/base64"
	"io"
	"os"
)

// HashMD5String 获取字符串的MD5值
func HashMD5String(oriString string) string {
	hash := md5.New()
	hash.Write([]byte(oriString))
	cipherStr := hash.Sum(nil)
	return base64.StdEncoding.EncodeToString(cipherStr)
}

// HashMD5File 获取文件的MD5值
func HashMD5File(file *os.File) (string, error) {
	hash := md5.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	hashInBytes := hash.Sum(nil)
	hashValue := base64.StdEncoding.EncodeToString(hashInBytes)
	return hashValue, nil
}

// HashSHA256String 获取字符串的SHA256值
func HashSHA256String(oriString string) string {
	hash := sha256.New()
	hash.Write([]byte(oriString))
	cipherStr := hash.Sum(nil)
	return base64.StdEncoding.EncodeToString(cipherStr)
}

// HashSHA256File 获取文件的SHA256值
func HashSHA256File(file *os.File) (string, error) {
	hash := sha256.New()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	hashInBytes := hash.Sum(nil)
	hashValue := base64.StdEncoding.EncodeToString(hashInBytes)
	return hashValue, nil
}

// HashHmacMD5String 获取字符串的Hmac-MD5值
func HashHmacMD5String(oriString string, secret string) string {
	key := []byte(secret)
	hash := hmac.New(md5.New, key)
	hash.Write([]byte(oriString))
	cipherStr := hash.Sum(nil)
	return base64.StdEncoding.EncodeToString(cipherStr)
}

// HashHmacMD5File 获取文件的Hmac-MD5值
func HashHmacMD5File(file *os.File, secret string) (string, error) {
	key := []byte(secret)
	hash := hmac.New(md5.New, key)
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	hashInBytes := hash.Sum(nil)
	hashValue := base64.StdEncoding.EncodeToString(hashInBytes)
	return hashValue, nil
}

// HashHmacSHA256String 获取字符串的Hmac-SHA256值
func HashHmacSHA256String(oriString string, secret string) string {
	key := []byte(secret)
	hash := hmac.New(sha256.New, key)
	hash.Write([]byte(oriString))
	cipherStr := hash.Sum(nil)
	return base64.StdEncoding.EncodeToString(cipherStr)
}

// HashHmacSHA256File 获取文件的Hmac-SHA256值
func HashHmacSHA256File(file *os.File, secret string) (string, error) {
	key := []byte(secret)
	hash := hmac.New(sha256.New, key)
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	hashInBytes := hash.Sum(nil)
	hashValue := base64.StdEncoding.EncodeToString(hashInBytes)
	return hashValue, nil
}
